#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
功能：使用： daemon_fromDB.py app_md5 建立Python Daemon 功能
"""
def OutPut(line):
    print ("[python ]:\t"+line)
    sys.stdout.flush()

#当前脚本目录
import sys,os
import dataFileReader
import numpy as np
from sklearn.preprocessing import StandardScaler
ScriptPath = os.path.split( os.path.realpath( sys.argv[0] ) )[0]
ScriptPath=ScriptPath+os.sep
OutPut("current work path："+ScriptPath)

app_md5= "f997016922b609ede885f609f1f3d484"; app_class= "LogisticRegression.src.main.java.LogisticRegressionApp";
if (len(sys.argv)>=3):
    app_md5=sys.argv[1]
    app_class=sys.argv[2]

#

dataFilePath=ScriptPath+".."+os.sep+"historyDataWhenDBnotAvaliable"+os.sep+"Application_Record_"+app_md5+"_"+app_class+".data"
modelPath=ScriptPath +".."+os.sep+ 'savedModels'+os.sep+"Application_Model_"+app_md5+"_"+app_class+os.sep

from sklearn.externals import joblib  # save the model in a file

f=open(dataFilePath)
count_of_groups=eval(f.readline())
f.close()

OutPut("读取分层模型")

OutPut("model path:"+modelPath)
modelList=[]
for i in range (count_of_groups):
    modelList.append(joblib.load(modelPath+'Model_%d.pkl'%(i)))

#恢复scaler
import re ;pattern="(\d+\.|\.\d+|\d+\.+\d)\s*(\d+\.|\.\d+|\d+\.+\d)\s*(\d+\.|\.\d+|\d+\.+\d)"

"""
#原计划使用Scaler data 
uList=[];sList=[];
scalerFile=open(modelPath+'scaler.data','r')
lines=scalerFile.read().splitlines()
for line in lines:
    res=re.findall(pattern,line)
    a=map(float,list(res[0]))
    b=map(float,list(res[1]))
    uList.append(a);sList.append(b)
    #print re.findall(pattern,line)
scalerFile.close()


def z(x,u,s):
    return (x-u)*1.0/s
"""

sys.stdout.flush()

#
count_of_groups,totalTimeList,groupConfList,groupTimeList= dataFileReader.readFile(dataFilePath)


scalerList=[]
for i in range(count_of_groups):
    # 重新训练Scaler
    scaler = StandardScaler()
    groupConf = np.array(groupConfList[i]).astype('float64')
    groupConf = scaler.fit_transform(groupConf)
    scalerList.append(scaler)
    # 重新训练Model ，但是之前Model 已经被选择过了
    model = modelList[i]
    model.fit(groupConf, groupTimeList[i])


'''
守护进程开一个不停止的循环，使用标准输入和标准输出进行数据交互
'''
OutPut("prediction  start!")
while True:
    str= raw_input("Enter your input: ");
    input_list=str.split()
    #print  input_list
    test_list=[]
    for s in input_list:
      if s!="":
           test_list.append(eval(s))
    print test_list
    #对参数进行划分
    group1=test_list[:-2]
    group2=test_list[-2:-1]
    group3=test_list[-1:]

    inputLists=[[group1],[group2],[group3]] #二维列表
    retList=[]

    for i in range(count_of_groups):
        inputLists[i]=np.array(inputLists[i]).astype('float64')
        inputLists[i]=scalerList[i].transform(inputLists[i])
        retList.append(modelList[i].predict(inputLists[i])[0])

    print  ('[prediction results]:\t%d\t%d\t%d'%(round(retList[0]),round(retList[1]),round(retList[2])))
    sys.stdout.flush()
#48 1 0 3072 5120 1 0 12 2 0 70

